import { useUserStore } from '@/stores'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login/index.vue'),
      name: 'login',
      meta: {
        title: '登录',
      },
    },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        {
          path: 'home',
          component: () => import('@/views/Home/index.vue'),
          name: 'home',
          meta: {
            title: '首页',
          },
        },
        {
          path: 'article',
          component: () => import('@/views/Article/index.vue'),
          meta: {
            title: '健康百科',
          },
        },
        {
          path: 'notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: {
            title: '消息中心',
          },
        },
        {
          path: 'user',
          component: () => import('@/views/User/index.vue'),
          name: 'user',
          meta: {
            title: '我的',
          },
        },
        {
          path: 'order',
          component: () => import('@/views/order/index.vue'),
          name: 'order',
          meta: {
            title: '全部订单',
          },
        }
      ],
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientInfo.vue'),
      meta: { title: '家庭档案' },
    },
    {
      path: '/consult/fast',
      component: () => import('@/views/Consult/ConsultFast.vue'),
      meta: { title: '极速问诊' },
    },
    {
      path: '/consult/dep',
      component: () => import('@/views/Consult/ConsultDep.vue'),
      meta: { title: '选择科室' },
    },
    {
      path: '/consult/illness',
      component: () => import('@/views/Consult/ConsultIllness.vue'),
      meta: { title: '病情描述' },
    },
    {
      path: '/consult/pay',
      component: () => import('@/views/Consult/ConsultPay.vue'),
      meta: { title: '问诊支付' }
    },
    {
      path: '/room',
      component: () => import('@/views/Room/index.vue'),
      meta: { title: '问诊室' }
    },
    {
      path: '/user/consult',
      component: () => import('@/views/User/ConsultOrder.vue'),
      meta: { title: '问诊记录' }
    },
    {
      path: '/user/consult/:id',
      component: () => import('@/views/User/ConsultDetail.vue'),
      meta: { title: '问诊详情' }
    }
  ],
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  const store = useUserStore()
  // 白名单 登录，注册[未开发]
  const whiteList = ['/login', '/register']
  // 如果没有token 也不在白名单内，则强制返回登录
  if (!store.user?.token && !whiteList.includes(to.path)) {
    return next('/login')
  } else {
    next()
  }
})

// 后置路由守卫
router.afterEach((to) => {
  // 处理标题
  document.title = `医疗门诊-${to.meta.title || ''}`
})

export default router
